﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iHouse.Model.Data;
using iHouse.Resource;

namespace iHouse.Web.Infrastructure
{
    public class NoteBinder : IModelBinder
    {
        #region IModelBinder Members

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            string title = request.Form.Get("Title");
            if (string.IsNullOrEmpty(title))
            {
                bindingContext.ModelState.AddModelError("Title", Resources.ExceptionNoteWithTitle);
            }

            Note note = new Note
            {
                Title = title,
                Description = request.Form.Get("Description"),
                Reference = request.Form.Get("Reference"),
                CategoryID = Convert.ToInt32(request.Form.Get("CategoryID"))
            };

            return note;
        }

        #endregion
    }

    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]
    public sealed class NoteBinderAttribute : CustomModelBinderAttribute
    {
        internal const AttributeTargets ValidTargets = AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Parameter;

        public override IModelBinder GetBinder()
        {
            return new NoteBinder();
        }
    }
}
